//
//  XFYLocalData.m
//  SDKSample
//
//  Created by 小肥羊 on 15/6/3.
//  Copyright (c) 2015年 Zhu‘s Game House. All rights reserved.
//

#import "XFYLocalData.h"

@implementation XFYLocalData

#pragma mark - 单例
+ (XFYLocalData *)sharedManager;
{
    static XFYLocalData *sharedAccountManagerInstance = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        sharedAccountManagerInstance = [[self alloc] init];
        [sharedAccountManagerInstance initValue];
    });
    return sharedAccountManagerInstance;
}

- (void)initValue
{
    self.db = [FMDatabase databaseWithPath:DATABASE_PATH];
    [self.db open];
    //创建用户表
    NSString *createFragmentTable = @"CREATE TABLE IF NOT EXISTS 'FragmentDataTable' ('FragmentData' VARCHAR PRIMARY KEY NOT NULL  UNIQUE )";
    if ([self.db executeUpdate:createFragmentTable]) {
        NSLog(@"创建碎片数据表");
    } else {
        NSLog(@"创建碎片数据表失败");
    }
    [self.db close];
}

#pragma mark - 开启关闭
+ (BOOL)openDB
{
    if ([[XFYLocalData sharedManager].db open]) {
        NSLog(@"数据库打开");
        return YES;
    } else {
        NSLog(@"数据库打开失败");
        return NO;
    }
}
+ (BOOL)closeDB
{
    if ([[XFYLocalData sharedManager].db close]) {
        NSLog(@"数据库关闭");
        return YES;
    } else {
        NSLog(@"数据库关闭失败");
        return NO;
    }
}

#pragma mark - 数据操作
/*! @brief 添加碎片数据 */
- (BOOL)addFragmentData:(NSString *)fragmentData {
    if (!fragmentData || [fragmentData isEqualToString:@""]) {
        NSLog(@"不能添加空数据");
        return NO;
    }
    NSString *addFragmentData = @"INSERT INTO 'FragmentDataTable' ('FragmentData') VALUES (?)";
    if ([self.db executeUpdate:addFragmentData,fragmentData]) {
        NSLog(@"添加");
        return YES;
    } else {
        NSLog(@"添加失败");
        return NO;
    }
}

/*! @brief 修改碎片数据 */
- (BOOL)modifyFragmentData:(NSString *)oldData fragmentData:(NSString *)newData {
    if (!newData || [newData isEqualToString:@""]) {
        NSLog(@"不能添加空数据");
        return NO;
    }
    NSString *modifyFragmentData = @"update FragmentDataTable set FragmentData = ? where FragmentData = ?";
    if ([self.db executeUpdate:modifyFragmentData,newData,oldData]) {
        NSLog(@"修改");
        return YES;
    } else {
        NSLog(@"修改失败");
        return NO;
    }
}

/*! @brief 删除碎片数据 */
- (BOOL)deleteFragmentData:(NSString *)data
{
    NSString *queryString = @"delete from FragmentDataTable where FragmentData = ?";
    if ([self.db executeUpdate:queryString,data]) {
        NSLog(@"删除");
        return YES;
    } else {
        NSLog(@"删除失败");
        return NO;
    }
}

/*! @brief 查找碎片数据 */
- (FMResultSet *)searchAllFragmentData {
    NSString *queryString=@"select * from FragmentDataTable";
    return [self.db executeQuery:queryString];
}

@end
